package cn.tedu.project.oa.sys.user.controller;


import cn.tedu.project.oa.base.exception.CaptchaException;
import cn.tedu.project.oa.base.response.JsonResult;
import cn.tedu.project.oa.base.response.StatusCode;
import cn.tedu.project.oa.sys.user.service.impl.CaptchaService;
import cn.tedu.project.oa.sys.user.pojo.vo.CaptchaVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Api(tags = "02.验证码")
@RestController
@RequestMapping("/oa/user/login")
public class CaptchaController {

    @Autowired
    private DefaultKaptcha producer;

    @Autowired
    private CaptchaService captchaService;


    @ApiOperation(value = "获取验证码")
    @GetMapping("/captcha")
    public JsonResult kaptcha() throws CaptchaException {
        //生成文字验证码
        String content = producer.createText();
        //生成图片验证码
        ByteArrayOutputStream outputStream = null;
        BufferedImage image = producer.createImage(content);

        outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            throw new CaptchaException(StatusCode.CODE_WRITE_ERROR);
        }

        //对字节数组进行base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Img = "data:image/jpeg;base64," + encoder.encode(outputStream.toByteArray()).replace("\n", "").replace("\r", "");

        //进行验证码业务处理，缓存到redis
        CaptchaVO captchaVO = captchaService.cacheCaptcha(content);
        captchaVO.setBase64Img(base64Img);
        return JsonResult.ok(captchaVO);
    }

}
